<template>
  <el-dialog
    :visible="showDialog"
    :title="form.id ? '编辑角色' : '添加角色'"
    @close="onCancel"
  >
    <el-form label-width="100px" :model="form" :rules="rules" ref="form">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="form.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="form.roleDesc"></el-input>
      </el-form-item>
    </el-form>
    <el-row type="flex" justify="end">
      <el-button size="small" @click="onCancel">取消</el-button>
      <el-button size="small" type="primary" @click="confirm">确定</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import { addRoles, editRoles } from '@/api/roles'
export default {
  data () {
    return {
      form: {
        roleName: '', // 角色名称
        roleDesc: '' // 角色描述
      },
      rules: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      editId: ''
    }
  },
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    onCancel () {
      this.form = {}
      this.$refs.form.resetFields()
      this.$emit('update:showDialog', false)
    },
    async confirm () {
      try {
        await this.$refs.form.validate()
        if (this.form.id) {
          // 编辑
          await editRoles(this.form)
          this.$message.success('编辑成功')
        } else {
          //  添加
          await addRoles(this.form)
          this.$message.success('添加成功')
        }
        this.$parent.getList()
        this.$emit('update:showDialog', false)
      } catch (err) {
        console.log(err)
      }
    },
    getDetail (roles) {
      this.form = JSON.parse(JSON.stringify(roles))
    }
  }
}
</script>

<style>
</style>
